package xcmg.device.web.agentApply;


import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.enums.AgentApplyStatusEnum;
import xcmg.device.service.agentApply.AgentApplyService;
import xcmg.device.service.vo.agentApply.AgentApplyVO;
import xcmg.device.service.vo.agentApply.ApplyAttachDelVO;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;


/**
 * @author wangyong
 */
@RestController
@RequestMapping("/agentApply")
public class AgentAppplyController extends BasicController {

  @Autowired
  private AgentApplyService agentApplyService;

  @ResponseBody
  @RequestMapping(value = "/saveStore", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "保存代理商门店申请")
  public ActionResult saveStore(HttpServletRequest request) {
    try {
      AgentApplyVO agentApplyVO = new AgentApplyVO();
      agentApplyVO = assemblyAgentApply(request, agentApplyVO);
      agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_STORE);
      agentApplyVO.setStatus(AgentApplyStatusEnum.DRAFT.getStatus());
      agentApplyService.save(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @ResponseBody
  @RequestMapping(value = "/commitStore", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "提交代理商门店申请")
  public ActionResult commitStore(HttpServletRequest request) {
    try {
      AgentApplyVO agentApplyVO = new AgentApplyVO();
      agentApplyVO = assemblyAgentApply(request, agentApplyVO);
      agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_STORE);
      agentApplyVO.setStatus(AgentApplyStatusEnum.WAIT_AUDIT.getStatus());
      agentApplyService.save(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @ResponseBody
  @RequestMapping(value = "/saveExhibition", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "保存代理商展会申请")
  public ActionResult saveExhibition(HttpServletRequest request) {
    try {
      AgentApplyVO agentApplyVO = new AgentApplyVO();
      agentApplyVO = assemblyAgentApply(request, agentApplyVO);
      agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_EXHIBITION);
      agentApplyVO.setStatus(AgentApplyStatusEnum.DRAFT.getStatus());
      agentApplyService.save(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  private AgentApplyVO assemblyAgentApply(HttpServletRequest request, AgentApplyVO agentApplyVO)
      throws Exception {
    agentApplyVO.setFiles(analysisMultFilesByRequest(request));
    agentApplyVO.setApplyDesc(request.getParameter("applyDesc"));
    agentApplyVO.setTitle(request.getParameter("title"));
    agentApplyVO.setReceiveOrgId(request.getParameter("receiveOrgId"));
    if (StringUtils.isBlank(request.getParameter("orgId"))) {
      agentApplyVO.setOrgId(getOrgId());
    } else {
      agentApplyVO.setOrgId(request.getParameter("orgId"));
    }
    agentApplyVO.setCreateId(getUserId());
    return agentApplyVO;
  }

  private List<MultipartFile> analysisMultFilesByRequest(HttpServletRequest request)
      throws Exception {
    List<MultipartFile> files = new ArrayList<>();
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    Iterator<String> iter = multiRequest.getFileNames();
    while (iter.hasNext()) {
      // 取得上传文件
      MultipartFile file = multiRequest.getFile(iter.next());
      if (null != file) {
        files.add(file);
      }
    }
    if (files.size() >= 10) {
      throw new Exception("单次上传数量必须小于10");
    }
    return files;
  }

  @ResponseBody
  @RequestMapping(value = "/commitExhibition", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "提交代理商展会申请")
  public ActionResult commitExhibition(HttpServletRequest request) {
    try {
      AgentApplyVO agentApplyVO = new AgentApplyVO();
      agentApplyVO = assemblyAgentApply(request, agentApplyVO);
      agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_EXHIBITION);
      agentApplyVO.setStatus(AgentApplyStatusEnum.WAIT_AUDIT.getStatus());
      agentApplyService.save(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/listExhibition", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "展会申请列表")
  public ActionResult listExhibition(@RequestBody SearchCommonVO<AgentApplyVO> condition)
      throws Exception {
    AgentApplyVO agentApplyVO = condition.getFilters();
    agentApplyVO.setOrgId(getOrgId());
    agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_EXHIBITION);
    condition.setFilters(agentApplyVO);
    PageCommonVO pageCommonVO = agentApplyService.list(condition);
    return actionValueResult(pageCommonVO.getPageInfo());
  }

  @RequestMapping(value = "/listStore", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "门店申请列表")
  public ActionResult listStore(@RequestBody SearchCommonVO<AgentApplyVO> condition)
      throws Exception {
    AgentApplyVO agentApplyVO = condition.getFilters();
    agentApplyVO.setOrgId(getOrgId());
    agentApplyVO.setApplyType(AgentApplyVO.APPLY_TYPE_STORE);
    condition.setFilters(agentApplyVO);
    PageCommonVO pageCommonVO = agentApplyService.list(condition);
    return actionValueResult(pageCommonVO.getPageInfo());
  }

  @ResponseBody
  @RequestMapping(value = "/uploadAttach", method = RequestMethod.POST)
  @ApiOperation(value = "单个附件信息上传")
  @FastMappingInfo(needLogin = true)
  public ActionResult uploadAttach(HttpServletRequest request) throws Exception {
    try {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
      String id = request.getParameter("id");
      String type = StringUtils.isBlank(request.getParameter("type")) ?"0": request.getParameter("type");
      if (StringUtils.isBlank(id)) {
        return new ActionResult(ErrorCode.Failure.getCode(), "未获取到id");
      }
      agentApplyService.uploadFile(id, file,Integer.valueOf(type));
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/deleteAttach", method = RequestMethod.GET)
  @ApiOperation(value = "单个附件信息删除")
  @FastMappingInfo(needLogin = true)
  public ActionResult deleteAttach(String attachId, String applyId) {
    try {
      agentApplyService.deleteAttachment(attachId, applyId);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/deleteAttachs", method = RequestMethod.POST)
  @ApiOperation(value = "附件批量删除")
  @FastMappingInfo(needLogin = true)
  public ActionResult deleteAttach(@RequestBody ApplyAttachDelVO delVO) {
    try {
      if (null == delVO || StringUtils.isBlank(delVO.getApplyId()) || CollectionUtils
          .isEmpty(delVO.getAttachIds())) {
        return new ActionResult(ErrorCode.Failure.getCode(), "参数不能未空");
      }
      for (String attachId : delVO.getAttachIds()) {
        agentApplyService.deleteAttachment(attachId, delVO.getApplyId());
      }
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/revoke", method = RequestMethod.GET)
  @ApiOperation(value = "撤回")
  @FastMappingInfo(needLogin = true)
  public ActionResult revoke(String applyId) {
    try {
      agentApplyService.revoke(applyId);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/firstAudit", method = RequestMethod.POST)
  @ApiOperation(value = "初审通过")
  @FastMappingInfo(needLogin = true)
  public ActionResult firstAudit(@RequestBody AgentApplyVO applyVO) {
    try {
      applyVO.setStatus(AgentApplyStatusEnum.FIRST_AUDIT_PASSED.getStatus());
      applyVO.setAuditId(getUserId());
      agentApplyService.audit(applyVO, AgentApplyVO.FIRST_AUDIT_TYPE);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/finalAudit", method = RequestMethod.POST)
  @ApiOperation(value = "终审通过")
  @FastMappingInfo(needLogin = true)
  public ActionResult finalAudit(@RequestBody AgentApplyVO applyVO) {
    try {
      applyVO.setStatus(AgentApplyStatusEnum.FINAL_AUDIT_PASSED.getStatus());
      applyVO.setAuditId(getUserId());
      applyVO.setExhibitionStatus(AgentApplyVO.EXHIBITION_STATUS_PROCESSING);
      agentApplyService.audit(applyVO, AgentApplyVO.FINAL_AUDIT_TYPE);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/auditReturn", method = RequestMethod.POST)
  @ApiOperation(value = "返回修改")
  @FastMappingInfo(needLogin = true)
  public ActionResult auditReturn(@RequestBody AgentApplyVO applyVO) {
    try {
      applyVO.setStatus(AgentApplyStatusEnum.RETURN_UPDATE.getStatus());
      applyVO.setAuditId(getUserId());
      agentApplyService.audit(applyVO, AgentApplyVO.AUDIT_RETURN);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/finish", method = RequestMethod.GET)
  @ApiOperation(value = "完结")
  @FastMappingInfo(needLogin = true)
  public ActionResult finish(String applyId) {
    try {
      agentApplyService.finish(applyId, getUserId());
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/reject", method = RequestMethod.GET)
  @ApiOperation(value = "驳回")
  @FastMappingInfo(needLogin = true)
  public ActionResult reject(String applyId) {
    try {
      agentApplyService.reject(applyId, getUserId());
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/listSapComs", method = RequestMethod.GET)
  @ApiOperation(value = "获取代理商对应的主机厂信息")
  @FastMappingInfo(needLogin = true)
  public ActionResult listSapComByDealer() {
    try {
      return actionValueResult(agentApplyService.listSapComByDealer(getOrgId()));
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
  }

  @RequestMapping(value = "/updateSave", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "修改页面-保存(草稿状态)")
  public ActionResult updateSave(@RequestBody AgentApplyVO agentApplyVO) {
    try {
      agentApplyVO.setCreateId(getUserId());

      agentApplyVO.setStatus(AgentApplyStatusEnum.DRAFT.getStatus());
      agentApplyService.update(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/updateCommit", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "修改页面-提交(待初审状态)")
  public ActionResult updateCommit(@RequestBody AgentApplyVO agentApplyVO) {
    try {
      agentApplyVO.setCreateId(getUserId());
      agentApplyVO.setStatus(AgentApplyStatusEnum.WAIT_AUDIT.getStatus());
      agentApplyService.update(agentApplyVO);
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/exhibitionEndCommit", method = RequestMethod.POST)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "展会结束后提交")
  public ActionResult exhibitionEndCommit(@RequestBody AgentApplyVO agentApplyVO) {
    if (null == agentApplyVO){
      return actionResult(ErrorCode.IllegalArument);
    }
    agentApplyVO.setCreateId(getUserId());
    return actionResult(agentApplyService.exhibitionEndCommit(agentApplyVO));
  }

  @RequestMapping(value = "/item", method = RequestMethod.GET)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "详情")
  public ActionResult listExhibition(String id) throws Exception {
    return actionValueResult(agentApplyService.item(id));
  }

  @RequestMapping(value = "/deleteApply", method = RequestMethod.GET)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "删除申请")
  public ActionResult deleteApply(String applyId) {
    try {
      agentApplyService.deleteApply(applyId, getUserId());
    } catch (Exception e) {
      return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
    }
    return actionResult(ErrorCode.Success);
  }

  @RequestMapping(value = "/downloadAttach", method = RequestMethod.GET)
  @FastMappingInfo(needLogin = true)
  @ApiOperation(value = "单个附件信息下载")
  public void downloadAttach(@RequestParam("attachId") String attachId,
      @RequestParam("applyId") String applyId) throws Exception {
    agentApplyService.downloadAttach(attachId, applyId);
  }
}
